from khronos.statistics.plotter import get_plotter

class FTable(dict):
    """This class implements a simple frequency table. It may be consulted for absolute and 
    relative frequencies of values."""
    def __init__(self):
        dict.__init__(self)
        self.__total = 0.0
        
    def __repr__(self):
        return self.__class__.__name__ + dict.__repr__(self)
        
    def clear(self):
        dict.clear(self)
        self.__total = 0.0
        
    def collect(self, value, weight=1.0):
        assert weight >= 0.0
        try:
            self[value] += weight
        except KeyError:
            self[value] = weight
        self.__total += weight
        
    def merge(self, ftable):
        if not isinstance(ftable, FTable):
            raise TypeError("expected FTable")
        for v, f in ftable.iteritems():
            self.collect(v, f)
            
    def abs_freq(self, value):
        return self.get(value, 0.0)
        
    def rel_freq(self, value):
        if self.__total == 0.0:
            return 0.0
        return self.get(value, 0.0) / self.__total
        
    def total(self):
        return self.__total
        
    def report(self, display=True):
        fmt = "%20s -> abs_freq = %f, rel_freq = %f"
        lines = [object.__repr__(self)]
        for value, freq in sorted(self.iteritems()):
            lines.append(fmt % (value, freq, freq / self.__total))
        report = "\n".join(lines)
        if display:
            print report
        else:
            return report
            
    # -----------------------------------------------
    # Plotting methods
    def pie_chart(self, target=None, **kwargs):
        return get_plotter(target).pie_chart(self.keys(), self.values(), **kwargs)
        
    def bar_chart(self, target=None, **kwargs):
        return get_plotter(target).bar_chart(self.keys(), self.values(), **kwargs)
        
    def pareto_chart(self, target=None, **kwargs):
        return get_plotter(target).pareto_chart(self.keys(), self.values(), **kwargs)
        
    def histogram(self, target=None, **kwargs):
        return get_plotter(target).histogram(self.keys(), self.values(), **kwargs)
        